package com.hospicpc.demos.controller;


import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.FollowUser;
import com.hospicpc.demos.entity.UserInfo;
import com.hospicpc.demos.service.Impl.FollowUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/followUser")
public class FollowUserController {
    @Autowired
    FollowUserServiceImpl followUserService;

    /**
     * 获取关注列表
     * @param id
     * @return
     */
    @GetMapping("/getList")
    public Result getList(@RequestParam("id") Long id) {

        List<UserInfo> list = followUserService.getList(id);

        return  Result.success(list);
    }


    /**
     * 关注用户
     * @param followUser
     * @return
     */
    @PostMapping("/add")
    public Result addCollectUser(@RequestBody  FollowUser  followUser) {
        //获取数据
        //文章id
        Long fromArticleId = followUser.getFromArticleId();
        //作者id
        Long toUserId = followUser.getToUserId();
        //用户id
        Long userId = followUser.getUserId();
        //文章类型,0代表ai文章，1代表普通文章
        Integer articleType = followUser.getArticleType();

        boolean res;

        //判断数据是否存在
       FollowUser one = followUserService.lambdaQuery().select(FollowUser::getId)
                .eq(FollowUser::getUserId, userId)
                .eq(FollowUser::getToUserId, toUserId).one();

        //存在,改变状态
        if(one != null) {
            res = followUserService.lambdaUpdate().eq(FollowUser::getUserId,userId)
                    .eq(FollowUser::getToUserId,toUserId)
                    .setSql("status = 1 , article_type = " + articleType)
                    .update();
        } else {
            //不存在,新插入数据
            res = followUserService.save(followUser);
        }

        if(res) return Result.success("关注成功");
        else  return Result.error("服务异常");

    }

    /**
     * 取消关注用户
     * @param followUser
     * @return
     */
    @PostMapping("/del")
    public Result delCollectUser(@RequestBody FollowUser followUser) {
        //获取数据
        //作者id
        Long toUserId = followUser.getToUserId();
        //用户id
        Long userId = followUser.getUserId();

        boolean res = followUserService.lambdaUpdate().eq(FollowUser::getUserId,userId)
                .eq(FollowUser::getToUserId,toUserId)
                .setSql("status = 0")
                .update();

        if(res) return Result.success("关注成功");
        else  return Result.error("服务异常");

    }

}
